package net.stuffrepos.bricknetcenter.http.util;

import java.lang.reflect.InvocationTargetException;
import java.util.LinkedList;
import java.util.List;
import net.stuffrepos.bricknetcenter.http.HttpParser;
import net.stuffrepos.bricknetcenter.http.HttpRequest;

/**
 *
 * @author Eduardo H. Bogoni <eduardobogoni@gmail.com>
 */
public class HttpParserHelper {

    public static HttpParser createParser(HttpRequest request) {

        try {
            return request.getParserClass().getConstructor(
                    getArgumentsTypes(request)).newInstance(
                    request.getParserArguments());

        } catch (NoSuchMethodException ex) {
            throw new RuntimeException(ex);
        } catch (SecurityException ex) {
            throw new RuntimeException(ex);
        } catch (InstantiationException ex) {
            throw new RuntimeException(ex);
        } catch (IllegalAccessException ex) {
            throw new RuntimeException(ex);
        } catch (IllegalArgumentException ex) {
            throw new RuntimeException(ex);
        } catch (InvocationTargetException ex) {
            throw new RuntimeException(ex);
        }
    }

    private static Class[] getArgumentsTypes(HttpRequest request) {
        List<Class> argumentsTypes = new LinkedList<Class>();
        for (Object argument : request.getParserArguments()) {
            argumentsTypes.add(argument.getClass());
        }
        return argumentsTypes.toArray(new Class[0]);
    }
}
